# -*- coding = utf-8 -*-
# @Time : 2023/9/17 10:19
# @Author : 龙王赘婿_彪少
# @File : tcp_server_copy.py
# @Software: PyCharm

# 功能：服务端模板
from socket import *
from threading import Thread
import time


class MYTCP:
    def __init__(self):
        self.ip = "127.0.0.1"
        self.port = 9000
        self.server_socket = socket(AF_INET, SOCK_STREAM)
        self.server_socket.bind((self.ip, self.port))
        print(f"server ip: {self.ip} port: {self.port } listening..............")
        self.server_socket.listen(5)
        self.client_socket, self.client_info = self.server_socket.accept()
        print(f"get client {self.client_info}")
        t1 = Thread(target=self.recv_thread)
        t2 = Thread(target=self.send_thread)
        t1.start()
        t2.start()
        t1.join()
        t2.join()
        self.client_socket.close()
        self.server_socket.close()

    # 接收线程
    def recv_thread(self):
        while True:
            recv_data = self.client_socket.recv(1024)  # 最大接收1024字节
            self.print_recv_data(recv_data)

    # 打印接收报文
    @staticmethod
    def print_recv_data(raw_data):
        print(f"recv：len = {len(raw_data)} data =", end=" ")
        for i in range(len(raw_data)):
            print(f"{raw_data[i]:02x}", end=" ")
        print()

    # 发送线程
    def send_thread(self):
        while True:
            time.sleep(0.05)
            key = input("输入指令：")
            if key == "1":
                send_data = "!AIVDO,1,1,,B,>69oQ@04@L`m1B0`mMA0L0,4*67\r\n"
                print(send_data)
                self.client_socket.send(send_data.encode("gbk"))
            elif key == "2":
                send_data = "!AIVDM,1,1,,A,869S8T@0@00QjT53Ep2ijP,4*27\r\n"
                print(send_data)
                self.client_socket.send(send_data.encode("gbk"))
            elif key == "3":
                send_data = "!AIVDM,1,1,,B,669S8TERHj9@0400@`MA0mB1LI@`,0*69\r\n"
                print(send_data)
                self.client_socket.send(send_data.encode("gbk"))
            elif key == "4":
                send_data = "!AIVDM,1,1,,A,<69S8TIRHj9@7D:14DPG=40,2*4E\r\n"
                print(send_data)
                self.client_socket.send(send_data.encode("gbk"))


if __name__ == "__main__":
    obj = MYTCP()
